package info.thereisonlywe.onenesspathfinder.user;

import info.thereisonlywe.core.data.DataHolder;
import info.thereisonlywe.core.io.FileIO;
import info.thereisonlywe.core.toolkit.StringToolkit;
import info.thereisonlywe.quran.text.QuranicText;
import info.thereisonlywe.quran.text.QuranicTextList;

import java.io.File;
import java.util.ArrayList;

/**
 * @author thereisonlywe
 */

public class RuntimeSettings extends DataHolder {

	public static final File RUNTIME_SETTINGS_FILE = new File("userdata"
			+ File.separator + "RuntimeSettings");

	private final String fields[] = { "font.size", "mushaf", "recitation.loop",
			"recitation.reciter", "recitation.textreciter", "scratchpad.text",
			"text", "section", "verse", "volume" };

	public boolean loaded = false;

	@SuppressWarnings("unused")
	private RuntimeSettings()
	{
	}

	public RuntimeSettings(boolean load) // true for get
	{
		if (load)
		{
			final String readsettings = FileIO
					.readString(RUNTIME_SETTINGS_FILE);
			if (readsettings != null && !readsettings.isEmpty())
			{
				load(readsettings);
				loaded = true;
			}
		}
	}

	public RuntimeSettings(final String savedsettings)
	{
		load(savedsettings);
		loaded = true;
	}

	private void load(final String savedsettings)
	{
		synchronized (super.map)
		{
			ArrayList<QuranicText> al = new ArrayList<>();
			for (String s : StringToolkit.splitLines(savedsettings))
			{
				if (!(s.isEmpty() || !s.contains("=")))
				{
					if (s.startsWith("text="))
					{
						al.add(new QuranicText(StringToolkit.splitStatement(s,
								'=')[1]));
						continue;
					}
					final String[] statement = StringToolkit.splitStatement(s,
							'=');
					super.map.put(statement[0], statement[1]);
				}
			}
			super.map.put("texts", al);
			al = null;
		}
	}

	@SuppressWarnings("unchecked")
	public ArrayList<QuranicText> getTexts()
	{
		synchronized (super.map)
		{
			return (ArrayList<QuranicText>) super.map.get("texts");
		}
	}

	/**
	 * Writes settings
	 * 
	 * @param name
	 */
	public void write()
	{
		StringBuilder sb = new StringBuilder();
		String s;
		for (int i = 0; i < fields.length; i++)
		{
			if (!fields[i].equals("text"))
			{
				s = fields[i] + "=" + get(fields[i]);
				sb.append(s);
				sb.append("\n");
			}
			else
			{
				for (int j = 0; j < QuranicTextList.getTextCount(); j++)
				{
					QuranicText qt = QuranicTextList.getText(j);
					if (qt.isLoaded())
					{
						s = "text=" + qt.toString() + "\n";
						sb.append(s);
					}
				}
			}
		}
		FileIO.write(sb.toString(), RUNTIME_SETTINGS_FILE, false);
		sb = null;
		s = null;
	}
}
